import React from 'react'
import { Map, Marker, Markers } from 'react-amap'

class MyMap extends React.Component {
	constructor(){
  	super();
    const _this = this;
    this.map = null;
    this.marker = null;
    this.geocoder = null;
    this.mapEvents = {
    	created(map){
      	_this.map = map;
         AMap.plugin('AMap.Geocoder',() => {
          _this.geocoder = new AMap.Geocoder({
              city: "010"//城市，默认：“全国”
          });
         })
      },
    	click(e){
      	const lnglat = e.lnglat;
      	_this.setState({
        	position: lnglat,
          currentLocation: 'loading...'
        });
        _this.geocoder && _this.geocoder.getAddress(lnglat, (status, result) => {
        	if (status === 'complete'){
          	if (result.regeocode){
              console.log(result)
              _this.setState({
                currentLocation: result.regeocode.addressComponent.township || '未知地点'
              });
              _this.props.getLocation(result.regeocode.addressComponent.township, result.regeocode.addressComponent.businessAreas[0].location)
            } else {
              _this.setState({
                currentLocation: '未知地点'
              });
            }
          } else {
            _this.setState({
                currentLocation: '未知地点'
            });
          }
        })
      }
    };
    this.markerEvents = {};
    this.state = {
    	position: null,
      currentLocation: '点击地图'
    }
  }

	render(){
    const { mapPosition, isNew } = this.props
  	return (
      isNew ?
      <Map events={this.mapEvents} zoom={15} amapkey={'788e08def03f95c670944fe2c78fa76f'} >
        <Marker
          position={this.state.position ? this.state.position : {
            longitude: 120, latitude: 30
          }}
          events={this.markerEvents}
        />
      </Map>
      :
      <Map center={mapPosition} events={this.mapEvents} zoom={15} amapkey={'788e08def03f95c670944fe2c78fa76f'} >
        <Marker position={this.state.position ? this.state.position : mapPosition} events={this.markerEvents}  />
      </Map>
      )
  }
}
export default MyMap
